package com.song.shop.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;

public class UDPClient {
    public static void main(String[] args) {
        DatagramSocket ds = null ;
        try {
            ds = new DatagramSocket();
            byte[] data = "你好，我是客户端".getBytes( Charset.forName("utf-8"));
            InetAddress inetAddress = InetAddress.getLocalHost();
            DatagramPacket dp = new DatagramPacket(data,data.length,inetAddress,8089);
            ds.setSoTimeout( 3000 );
            ds.send( dp );
            //接收服务端返回的数据
            byte[] reciveByte = new byte[1024];
            DatagramPacket responeDp = new DatagramPacket( reciveByte,reciveByte.length );
            ds.receive( responeDp );
            System.out.println("服务端返回的数据："+new String( responeDp.getData() ));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ds != null ){
                ds.close();
            }
        }
    }
}
